package com.xca.gsondemo.views;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xca.gsondemo.R;
import com.xca.gsondemo.adapter.MedalsAdapter;
import com.xca.gsondemo.entity.Olympic;
import com.xca.gsondemo.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

public class GoldFragment extends Fragment {
    private View goldFragment ;
    private ListView listView;
    private List<Olympic> mList = new ArrayList<>();
    private MedalsAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        goldFragment = inflater.inflate(R.layout.gold, container, false);
        listView = goldFragment.findViewById(R.id.g_list);

        testJsonParser();
        // 初始化适配器
        adapter = new MedalsAdapter(getContext(), R.layout.gold_item, mList);
        listView.setAdapter(adapter);


        return goldFragment;
    }


    private void testJsonParser() {
        String jsonStr = getJson("olympic.json");
        JsonObject jo = JsonParser.parseString(jsonStr).getAsJsonObject();
        JsonObject data = jo.get("result").getAsJsonObject();
        JsonArray array = data.get("medalsList").getAsJsonArray();
        for (JsonElement jsonElement : array) {
           Olympic olympic = new Olympic();
            olympic.setCountryid(jsonElement.getAsJsonObject().get("countryid").getAsString());
            olympic.setCountryname(jsonElement.getAsJsonObject().get("countryname").getAsString());
            olympic.setGold(jsonElement.getAsJsonObject().get("gold").getAsString());
            olympic.setSilver(jsonElement.getAsJsonObject().get("silver").getAsString());
            olympic.setBronze(jsonElement.getAsJsonObject().get("bronze").getAsString());
            olympic.setCount(jsonElement.getAsJsonObject().get("count").getAsString());
            olympic.setRank(jsonElement.getAsJsonObject().get("rank").getAsString());
            mList.add(olympic);
            Log.d("asdf", " ==name== " + olympic.getCountryname());
        }
    }

    private String getJson(String name) {
        if (getActivity() == null) return null; // 防止空指针异常
        String json = JsonUtils.getJsonFromAssets(getActivity(), name);
        Log.d("获取所有", "getJson: " + json);
        return json;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 清理成员变量
         goldFragment = null;
    }
}